package com.educate.ucenter.web.controller;

import com.educate.common.web.EmptyUtils;
import com.educate.common.web.R;
import com.educate.ucenter.model.bo.AccountBO;
import com.educate.ucenter.shiro.seesion.UserSession;
import com.educate.ucenter.shiro.seesion.UserSessionDao;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@Log4j2
@RestController
@RequestMapping("/sso")
public class SSOController {

    @Resource UserSessionDao userSessionDao;

    @PostMapping("/login")
    public R<String> login(@RequestBody AccountBO bo) {
        if (EmptyUtils.isNotEmpty(bo.getUid())) {
            UserSession session = userSessionDao.getSession(bo.getUid());
            if (session != null) {//其他安全判断
                return R.ok(session.getUserId());
            } else {
                return R.error(R.CODE_LOGIN_EXPIRE, "过期已过期,请重新登录");
            }
        }
        Assert.notNull(bo.getAccount(), "账号不能为空");
        Assert.notNull(bo.getPassword(), "密码不能为空");
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(bo.getAccount(),
                bo.getPassword());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        subject.login(usernamePasswordToken);
        String sessionId = session.getId().toString();
        userSessionDao.logined(sessionId);
        return R.ok(sessionId);
    }

    @RequestMapping("/notLogin")
    public R<String> notLogin() {
        return R.error(R.CODE_LOGIN_NOT, "请先登录");
    }

    @PostMapping("/needLogin")
    public R<String> needLogin(@RequestBody AccountBO bo) {
        return R.ok("已经登录" + bo.getAccount());
    }
}
